import { defaultVue, notification } from '../main';
import de from 'element-ui/src/locale/lang/de';
import eventBus from './eventBus';

let WsUtil = function() {
    let this_ = this;
    this.ws = null;
    this.buildConn = function(url,userId) {
        this_.ws = new WebSocket(`ws://${url}/websocket/${userId}`);


        this_.ws.onopen = function()
        {
            // Web Socket 已连接上，使用 send() 方法发送数据
            this_.ws.send("发送数据");
            /*notification({
                title:'提示',
                message:'数据发送中',
                duration:4000
            });*/
            //alert("数据发送中...");
        };

        this_.ws.onmessage = function (evt)
        {
            var received_msg = evt.data;
            //alert("数据已接收...");
            if(received_msg==='connSucc'){
                /*notification({
                    title:'提示',
                    message:'数据已接收,连接已建立',
                    duration:4000
                });*/
            }else if(received_msg==="somebodyAskLeaving"){
                //console.log(defaultVue.$route);

                eventBus.emit("refreshLeave");

                notification({
                    title:'提示',
                    message:received_msg,
                    duration:4000,
                    onClick:function() {
                        defaultVue.$router.push({
                            path:'/notice'
                        });
                    }
                });
            } else{
                notification({
                    title:'提示',
                    message:received_msg,
                    duration:4000,
                    onClick:function() {
                        defaultVue.$router.push({
                            path:'/notice'
                        });
                    }
                });
            }

        };

        /*this_.ws.onclose = function()
        {
            // 关闭 websocket
            alert("连接已关闭...");
        };*/
    }

}

var wsUtil = new WsUtil();
export default wsUtil;

